﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NAccounting.QueryObjects
{
    public enum LotStateOption
    { 
        Undefined = 'U',
        Opened = 'O',
        Closed = 'C'
    }

    public class LotQueryObject : QueryObject<Lot>
    {
        private TimePeriod _period;

        public LotStateOption StateOption { get; set; }
        public TimePeriod? Period { get; set; }

        public LotQueryObject(NAccountEntities context) 
            : base(context) 
        {
            StateOption = LotStateOption.Undefined;
        }

        public override PagedResult<Lot> Get(int pageIndex, int rows)
        {
            _period = Period != null ? Period.Value : Calendar.ThisMonth();

            if (StateOption == LotStateOption.Opened)
            {
                return GetOpened(pageIndex, rows);
            }
            else if (StateOption == LotStateOption.Closed)
            {
                return GetClosed(pageIndex, rows);
            }

            var lots = Context.Lots
                              .Where(x => x.StartPeriod >= _period.Start && x.EndPeriod <= _period.End)
                              .ToArray();

            return Get(pageIndex, rows, lots);
        }

        private PagedResult<Lot> GetOpened(int pageIndex, int rows)
        {
            var lots = Context.Lots
                          .Where(x => x.OpenDate.HasValue &&
                                     !x.CloseDate.HasValue &&
                                      x.StartPeriod >= _period.Start && x.EndPeriod <= _period.End)
                          .ToArray();

            return Get(pageIndex, rows, lots);
        }

        private PagedResult<Lot> GetClosed(int pageIndex, int rows)
        {
            var lots = Context.Lots
                          .Where(x => x.CloseDate.HasValue &&
                                      x.StartPeriod >= _period.Start && x.EndPeriod <= _period.End)
                          .ToArray();

            return Get(pageIndex, rows, lots);
        }

        private PagedResult<Lot> Get(int pageIndex, int rows, IEnumerable<Lot> lots)
        {
            var result = new PagedResult<Lot>
            {
                Total = lots.Count(),
                List = lots.OrderBy(x => x.Description)
                           .Skip(pageIndex * rows)
                           .Take(rows).ToArray()
            };

            return result;
        }
    }
}